# Classify Tor-based malware & benign connections (Python 3.7)

import csv
import sys, os
import math
import scipy
import time
import random
import operator
import argparse
import subprocess
import numpy as np
import loaders_binary as ll
import autogluon_classify as ag
import ML_classify as mlc
import loaders_multilabel as multitest
from sys import stdout
from sklearn import tree
from sklearn import metrics
import sklearn.metrics as skm
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.multiclass import OneVsRestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import precision_recall_fscore_support as score_multi
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler as MMS
from sklearn.preprocessing import StandardScaler
from collections import defaultdict
from itertools import chain

def check_outfolder(d):
	if "OUTPUT_FOLDER" in d:
		outfolder = d["OUTPUT_FOLDER"]
	else:
		curpath = os.getcwd()
		if not os.path.exists(curpath+"/output"):
			os.system("mkdir "+curpath+"/output")
			outfolder = curpath+"/output/"
	return outfolder

def main(d, topk=3, train=True, zeroday=False):
	print("Classifier Modes\n Mode 0: Binary Classification\n , Mode 1: Multi Label Multi Class\n")
	# 1. Read input
	[malfnames, benfnames, foldtotal, multiclass, maltotal, malinst, bentotal, hostfts] = ll.get_list(d)
	print("Malicious files: %d, Benign files: %d "%(len(malfnames), len(benfnames)))
	print("Extract Host fts? ", hostfts)

	# 2. Label instances
	if multiclass == 0:
		print("MODE: 0: TRAIN BINARY CLASSIFIER for Tor-based malware detection")
		# dt: {fpath: 0 or 1-> 0 for benign, 1 for malware}
		labeldt = ll.label_binary(malfnames, benfnames)

	elif multiclass == 1 and train == False:
		# Predict multilabel tags for zeroday malware instances only. Outputs: tag prediction and malware # label eg 0 for 0-1.cell
		# set multilabel= 1 and hostfts = True in options file
		print("MODE: 1: PREDICT malware class labels (eg: ransomware, worm, virus etc)")
		labeldt = ll.label_multiclass(d, malfnames, benfnames)
		featdf = ll.extract_features(labeldt, multiclass, hostfts, top=topk, trainmulti=False)
		print("Testing multilabel models on dataframe: ", featdf, featdf.size)
		multitest.test_models(featdf, topk)
		return
	else:
		assert multiclass == 1 and train == True
		print("MODE: 1: TRAIN multilabel models for MALWARE CLASS IDENTIFICATION")
		mllabel_op = mlc.main_ml(d, malfnames, benfnames, foldtotal, maltotal, malinst, topk, hostfts, multiclass)
		outfolder = check_outfolder(d)
		# result breakdown: [acc, hloss, mprec, mrecall, mf1, ctype, model]
		ll.output_multilabel(mllabel_op, outfolder, maltotal, malinst, multiclass, hostfts)
		# test_given_inst(mllabel_op) : Using multilabel models, classify test inst
		return

	# 3. Feature Extraction
	malinst += 1
	dataset = "D"+str(malinst)
	if train:
		print("PCAP SPLIT for: ", dataset)
		# PCAP/cell file SPLIT: 70% (train), 30% (test)
		checklist_train, checklist_test = ll.get_pcapsplit(labeldt, maltotal, bentotal, malinst, dataset)
		print("PCAPs (TRAIN): ", len(checklist_train))
		print("PCAPs (TEST): ", len(checklist_test))
		featdf_test = ll.extract_features(labeldt, multiclass, hostfts, top=topk, checklist=checklist_test)
		featdf_train = ll.extract_features(labeldt, multiclass, hostfts, top=topk, checklist=checklist_train)
	else:
		assert zeroday == True
		featdf = ll.extract_features(labeldt, multiclass, hostfts, top=topk)
		time.sleep(5)

	if train:
		# Binary Classification: TRAIN
		print("Training models with HOSTONLY fts")
		[ag_res1, ag_res2, fimp1, fimp2, cmatrix, bestmodel, perf, aucscore] = ag.main_ag(featdf_train, featdf_test, "target", malinst, hostfts)
		ff = open("output/BinaryTraining_D"+str(malinst)+".score", "w+")
		ll.output_avg(foldtotal, ag_res1, ag_res2, fimp1, fimp2, cmatrix, bestmodel, perf, aucscore, ff)
	else:
		# Binary Classification: TEST on Zeroday
		malinst = 5 # testing model trained on D5
		if hostfts:
			model = str(malinst)+"_True"
		else:
			model = str(malinst)+"_False"

		if not os.path.exists(os.getcwd()+"/AGmodels"):
			print("Models must be trained before testing! (Note: Trained models expected in 'AGmodels/'). Exiting.")
			sys.exit()

		curdir = os.getcwd()
		mpath = curdir+"/AGmodels/"
		stackmpath = curdir+"/AGmodels/stacked/"
		if multiclass == 0 and zeroday:
			ag.zerodaytest(featdf, "target", malinst, hostfts, mpath+model)
		return

	return

if __name__ == "__main__":
	parser = argparse.ArgumentParser(description='Tor-based Malware Detection')
	parser.add_argument('--options', nargs=1, metavar="STR", help='Options file name')
	parser.add_argument('--topk', nargs=1, metavar="INT", help='k value in topk (k = 1 or 3)')
	parser.add_argument('--train', action='store_true', help='Train models (Set MULTICLASS: 0 - Binary classification of connections, 1 - Malware labels classification) in options files')
	parser.add_argument('--zeroday', action='store_true', help='Zero day test (0: Detect malware connections, 2: Identify malware class labels')
	args = parser.parse_args()
	print(args, sys.argv)
	if not len(sys.argv) == 6:
		parser.print_help()
		print("Pls set all arguments (--options, --topk, --train/--zeroday)")
		sys.exit()

	print(args.options)
	if "options-" in args.options[0]:
		optfname = args.options[0]
	else:
		parser.print_help()
		print("Input options file (see sample 'options-' file)")
		sys.exit()

	if args.topk[0] == '1' or args.topk[0] == '3':
		top = int(args.topk[0])
	else:
		parser.print_help()
		print("Missing Argument! Top-k most active Tor connections, defaulting to k=3")
		top = 3

	d = ll.load_options(optfname)
	if args.train:
		# Training
		# 1. Train Autogluon models for binary classification & Multilabel models
		print(":Training Mode:")
		main(d, topk=top)

	elif args.zeroday:
		print(":Zeroday Testing Mode:")
		if "zeroday_binary" in optfname:
			print("Identify Tor malware connections (binary classifier)")
			# 2.1 Binary classification - Zeroday test
			main(d, train=False, zeroday=True)
		elif "zeroday_multilabel" in optfname:
			print("Identify malware class labels (multilabel classifier)")
			# 2.2 Multilabel tag prediction (multiclass mode = 1)
			main(d, topk=top, train=False)
		else:
			print("Incorrect options file used (use options-zeroday_binary(multiclass=0) or options-zeroday_multilabel(multiclass=1))")
			sys.exit()
